package com.xfapp.demos.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfapp.demos.common.Result;
import com.xfapp.demos.entity.Exam;
import com.xfapp.demos.entity.Question;
import com.xfapp.demos.service.IExamService;
import com.xfapp.demos.service.IQuestionService;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 存储用户考试记录的表 前端控制器
 * </p>
 *
 * @author jinYi
 * @since 2025-06-17
 */
@RestController
@RequestMapping("/exam")
public class ExamController {

    @Resource
    private IExamService examService;
    @Resource
    private IQuestionService questionService;

    /**
     * 考试记录不用批量保存（单保存）
     * @param exam
     * @return
     */
    @PostMapping("/saveOne")
    public Result save(@RequestBody Exam exam)
    {
        boolean saveResult = examService.save(exam);
        System.out.println("保存结果："+ exam.getUniKey());
        String uniKey = exam.getUniKey();
        if (!saveResult){
            return Result.error("-1","保存失败");
        }
        return Result.success(uniKey);
    }

    @GetMapping("/findOne/{uniKey}")
    public Result findOne(@PathVariable String uniKey)
    {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Exam> eq = queryWrapper.eq("uni_key", uniKey).eq("del_flag", 0);
        Exam exam = examService.getOne(eq);
        if (exam == null){
            return Result.error("-1","未找到该考试记录");
        }
        return Result.success(exam);
    }
    @GetMapping("/findList/{uniKey}")
    public Result findAll(@PathVariable String uniKey)
    {
        QueryWrapper<Exam> eq = new QueryWrapper<Exam>()
                .eq("uni_key", uniKey)
                .eq("del_flag", 0);
        Exam one = examService.getOne(eq);
        String questionsJson = one.getQuestions();
        String wrongLists = one.getWrongQuestions();
        String answerInfo = one.getAnswerInfo();
        Map parse = JSON.parseObject(answerInfo,new TypeReference<Map>(){});
        List idAndAnswer = (List)parse.get("idAndAnswer");
        List<Long> wrongs = JSON.parseObject(wrongLists, new TypeReference<List<Long>>() {});
        JSONObject questionsObj = JSON.parseObject(questionsJson);
        List<Long> ids = new ArrayList<>();
        for (String key : questionsObj.keySet()) {
            JSONArray array = questionsObj.getJSONArray(key);
            for (Object obj : array) {
                if (obj instanceof JSONObject) {
                    // 如果是 JSONObject，提取 id
                    Long id = ((JSONObject) obj).getLong("id");
                    if (id != null) {
                        ids.add(id);
                    }
                } else if (obj instanceof Number) {
                    // 如果是纯数字（Integer/Long），直接添加为 ID
                    ids.add(((Number) obj).longValue());
                }
                // 其它类型可以忽略或记录日志
            }
        }
        List<Question> questionList = questionService.list(new QueryWrapper<Question>().eq("del_flag",0)
                .in("id", ids));
        List<Question> wrongList = questionList.stream()
                .filter(question -> wrongs.contains(question.getId()))
                .collect(Collectors.toList());
        Map<String,List> map = new HashMap<>();
        map.put("questionList",questionList);
        map.put("wrongList",wrongList);
        map.put("answerList",idAndAnswer);
        System.out.println("question:" + questionList.size() + "wrongList" + wrongList.size());
        return Result.success(map);
    }
    @GetMapping("/getExamRecords/{userId}")
    public Result getExamRecords(@PathVariable Integer userId){

        List<Exam> examList = examService.list(
                new QueryWrapper<Exam>().eq("user_id",userId).eq("del_flag",0)
        );
        if(examList == null || examList.size() == 0){
            return Result.error("-1","没有考试记录");
        }

        // 转换考试记录为前端需要的格式
        List<Map<String, Object>> formattedList = new ArrayList<>();
        for (Exam exam : examList) {
            Map<String, Object> record = new HashMap<>();
            record.put("unikey", exam.getUniKey());
            record.put("submitTime", exam.getCreateTime());
            record.put("score", exam.getScore());
            record.put("pass", exam.getPassed() == 1 ? true : false);

            // 提取 answerInfo 中的 examTime
            String answerInfoStr = exam.getAnswerInfo();
            if (answerInfoStr != null && !answerInfoStr.isEmpty()) {
                try {
                    JSONObject answerInfo = JSON.parseObject(answerInfoStr);
                    if (answerInfo.containsKey("examTime")) {
                        record.put("duration", answerInfo.getString("examTime"));
                    } else {
                        record.put("duration", "00:00:00"); // 默认值
                    }
                } catch (Exception e) {
                    record.put("duration", "00:00:00"); // 解析失败时的默认值
                }
            } else {
                record.put("duration", "00:00:00"); // 默认值
            }

            formattedList.add(record);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("total", examList.size());
        response.put("list", formattedList);

        return Result.success(response);
    }
}
